import router, { resetRouter } from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { i18nRender } from '@/locales'
import { asyncRouterMap } from '@/config/router.config.js'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const allowList = ['login', 'register', 'registerResult'] // no redirect allowList
const loginRoutePath = '/user/login'
// const defaultRoutePath = '/dashboard/workplace'

// const routes = asyncRouterMap.find((item) => item.path === '/')
// let permissionList = store.state.user.info.permissionList.map(item => item.permissionCode)
// const menus = (routes && routes.children.filter(item => {
//   if(!item.meta.permissionCode){
//     return true
//   }
//   // 是否当前页面所需权限都在权限列表中、不在的过滤掉
//   const permissionCodeList = item.meta.permissionCode
//   return permissionCodeList.every(permissionCodeItem => permissionList.includes(permissionCodeItem))
// })) || []

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && typeof to.meta.title !== 'undefined' && setDocumentTitle(`${i18nRender(to.meta.title)} - ${domTitle}`)
  /* has token */
  // const token = storage.get(ACCESS_TOKEN)
  const token = window.sessionStorage.getItem(ACCESS_TOKEN)
  if (token) {
    if (to.path === loginRoutePath) {
      next()
      NProgress.done()
    } else {
      console.log(to.meta.permissionCode, 'to.meta.permissionCodeto.meta.permissionCodeto.meta.permissionCode')
      if (!to.meta.permissionCode) {
        next()
      } else {
        // const permissionCodeList = to.meta.permissionCode || []
        // let permissionList = store.state.user.info.permissionList.map(item => item.permissionCode)
        // 是否拥有当前页面所需权限list
        // console.log(permissionCodeList, 'permissionCodeListpermissionCodeListpermissionCodeListpermissionCodeList')
        // console.log(permissionList, 'permissionListpermissionListpermissionListpermissionListpermissionListpermissionList')
        // console.log(from.meta)
        next()
        // if (permissionCodeList.every(item => permissionList.includes(item))) {
        //   next()
        // } else {
        //   next({
        //     path: '/403'
        //   })
        // }
      }
    }
  } else {
    if (allowList.includes(to.name)) {
      // 在免登录名单，直接进入
      next()
    } else {
      next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
